<script setup>
import { ref, onMounted, getCurrentInstance, watch } from 'vue'
import { Search, ShoppingCart, User, Star, SwitchButton } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { listCategory, listCarousel, foundation } from '@/api'
import ShoppingCartComponent from '@/components/ShoppingCart.vue'

// 模拟分类数据
// 定义分类数据响应式变量
const categories = ref([])

// 获取分类数据
const fetchCategories = async () => {
  try {
    const res = await listCategory()
    categories.value = res.data.data
  } catch (error) {
    console.error('获取分类数据失败:', error)
    ElMessage.error('获取分类数据失败')
  }
}
// 产品数据
const allProducts = ref([])

const fetchAllProducts = async () => {
  try {
    const res = await foundation({ "categoryId": 0 })
    allProducts.value = res.data.data
  } catch (error) {
    console.error('获取首页数据失败:', error)
    ElMessage.error('获取首页数据失败')
  }
}
// 过滤后的产品数据
const products = ref(allProducts)

// 轮播图数据
const banners = ref([])

const fetchBanners = async () => {
  try {
    const res = await listCarousel()
    banners.value = res.data.data
  } catch (error) {
    console.error('获取轮播数据失败:', error)
    ElMessage.error('获取轮播数据失败')
  }
}
onMounted(() => {
  // 添加Promise.all确保并行请求
  Promise.all([
    fetchCategories().catch(e => e),
    fetchBanners().catch(e => e),
    fetchAllProducts().catch(e => e)
  ]).then(() => {
    console.log('分类数据:', categories.value)
    console.log('轮播数据:', banners.value)
    console.log('产品数据:', allProducts.value)
  })
  console.log('当前用户角色:', userRole.value)
  console.log('当前用户权限:', userPermissions.value)
})

// 搜索关键词
const searchKeyword = ref('')

// 当前选中的分类
const activeCategory = ref(0)


// 处理搜索功能
// API调用
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  // 跳转到搜索结果页面
  router.push({
    path: '/search',
    query: { keyword: searchKeyword.value.trim() }
  })
}

// API调用
const handleCategoryChange = (categoryId) => {
  activeCategory.value = categoryId
  console.log('切换分类:', categoryId)

  // 根据分类ID过滤产品
  const categoryIdNum = parseInt(categoryId)
  if (categoryIdNum === 0) {
    // 如果选择"全部"，显示所有产品
    fetchAllProducts()
  } else {
    // 否则根据分类ID过滤产品
    try {
      foundation({ "categoryId": categoryIdNum }).then(res => {
        products.value = res.data.data
        console.log('分类后数据:', products.value);
      });
    } catch (error) {
      console.error('获取分类后数据失败:', error)
      ElMessage.error('获取分类后数据失败')
    }
  }
}

// 引用购物车组件实例
const shoppingCartRef = ref(null)

// API调用
const addToCart = (product) => {
  console.log('添加到购物车:', product)
  // 调用购物车组件的addProduct方法
  if (shoppingCartRef.value && shoppingCartRef.value.addProduct) {
    shoppingCartRef.value.addProduct(product)
  } else {
    ElMessage.warning('购物车组件未加载')
  }
}

// API调用
const goToProductDetail = (productId) => {
  router.push({
    name: 'productDetail',
    params: { id: productId }
  })
}

// 直接导入store模块
import store from '@/store'

// 检查用户权限
const hasPermission = (permission) => {
  return store.hasPermission(permission)
}

// 获取当前用户角色
const userRole = ref(store.state.role)

// 获取当前用户权限列表
const userPermissions = ref(store.state.permissions)

// 路由实例
const router = useRouter()

// 购物车抽屉可见性
const cartDrawerVisible = ref(false)

// 打开购物车抽屉
const openCartDrawer = () => {
  cartDrawerVisible.value = true
}

// 跳转到个人中心
const goToUserProfile = () => {
  router.push('/profile')
}

// 跳转到商品管理页面
const goToProductManagement = () => {
  router.push('/product/management')
}

// 退出登录
const logout = () => {
  store.clearUser()
  router.push('/')
}

// API调用
const handleCheckout = () => {
  console.log('处理结算')
  // 这里可以跳转到结算页面
  // router.push('/checkout')
}

</script>

<template>
  <div class="user-home">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="container">
        <div class="logo-area">
          <img src="@/assets/logo.svg" alt="Logo" class="logo" />
          <h1>MyFootballShow</h1>
        </div>

        <div class="search-area">
          <el-input v-model="searchKeyword" placeholder="搜索你喜欢的球鞋" :prefix-icon="Search" @keyup.enter="handleSearch">
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </div>

        <div class="user-actions">
          <el-button type="text" :icon="ShoppingCart" @click="openCartDrawer">购物车</el-button>
          <el-button type="text" :icon="User" @click="goToUserProfile">个人中心</el-button>
          <el-button type="text" :icon="SwitchButton" @click="logout">
            退出登录
          </el-button>
        </div>
      </div>
    </div>

    <!-- 分类导航 -->
    <div class="category-nav">
      <div class="container">
        <el-menu mode="horizontal" :default-active="activeCategory.toString()" @select="handleCategoryChange"
          class="category-menu">
          <el-menu-item index="0">全部</el-menu-item>
          <el-menu-item v-for="category in categories" :key="category.id" :index="category.id.toString()">
            {{ category.name }}
          </el-menu-item>
        </el-menu>
      </div>
    </div>

    <!-- 轮播图 -->
    <div class="banner-section">
      <div class="container">
        <el-carousel height="400px">
          <el-carousel-item v-for="banner in banners" :key="banner.id">
            <img :src="banner.image" class="banner-image"/>
          </el-carousel-item>
        </el-carousel>
      </div>
    </div>
    <!-- 购物车组件 -->
    <ShoppingCartComponent ref="shoppingCartRef" v-model:visible="cartDrawerVisible" @checkout="handleCheckout" />

    <!-- 产品展示区 -->
    <div class="product-section">
      <div class="container">
        <h2 class="section-title">热门球鞋</h2>

        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="product in products" :key="product.id" class="product-col">
            <el-card class="product-card" :body-style="{ padding: '0px' }" @click="goToProductDetail(product.id)">
              <div class="product-img-container">
                <img :src="product.image" class="product-image" />
              </div>

              <div class="product-info">
                <h3 class="product-name">{{ product.name }}</h3>
                <p class="product-brand">{{ product.brand }}</p>

                <div class="product-price-row">
                  <span class="product-price">¥{{ product.price }}</span>
                  <span class="product-original-price">¥{{ product.originalPrice }}</span>
                </div>

                <div class="product-meta">
                  <span class="product-rating">
                    <el-icon>
                      <Star />
                    </el-icon> {{ product.rating }}
                  </span>
                  <span class="product-sales">销量 {{ product.sales }}</span>
                </div>

                <el-button type="primary" class="add-to-cart-btn" @click="addToCart(product)">
                  加入购物车
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>

  <!-- 购物车抽屉组件 -->
  <ShoppingCartComponent ref="shoppingCartRef" v-model:visible="cartDrawerVisible" @checkout="handleCheckout" />
</template>

<style scoped>
.user-home {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 30px;
}

/* 顶部导航栏 */
.top-navbar {
  background-color: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.top-navbar .container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo-area {
  display: flex;
  align-items: center;
}

.logo {
  width: 50px;
  height: 50px;
  margin-right: 15px;
}

.logo-area h1 {
  font-size: 24px;
  margin: 0;
  color: #333;
  font-weight: 600;
}

.search-area {
  flex: 1;
  max-width: 600px;
  margin: 0 40px;
}

.user-actions {
  display: flex;
  gap: 15px;
}

/* 分类导航 */
.category-nav {
  background-color: white;
  border-bottom: 1px solid #eee;
  margin-bottom: 20px;
}

.category-menu {
  border-bottom: none;
}

/* 轮播图 */
.banner-section {
  margin-bottom: 40px;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 产品区域 */
.product-section {
  padding: 20px 0 40px;
}

.section-title {
  font-size: 28px;
  margin-bottom: 30px;
  color: #333;
  position: relative;
  padding-left: 18px;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 5px;
  height: 20px;
  background-color: #409EFF;
  border-radius: 2px;
}

.product-col {
  margin-bottom: 20px;
}

.product-card {
  transition: all 0.3s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

.product-img-container {
  height: 240px;
  overflow: hidden;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.product-card:hover .product-image {
  transform: scale(1.05);
}

.product-info {
  padding: 15px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.product-name {
  font-size: 18px;
  margin: 0 0 8px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-brand {
  font-size: 14px;
  color: #666;
  margin: 0 0 10px;
}

.product-price-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.product-price {
  font-size: 20px;
  font-weight: bold;
  color: #f56c6c;
  margin-right: 10px;
}

.product-original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 13px;
  color: #666;
}

.product-rating {
  display: flex;
  align-items: center;
}

.product-rating .el-icon {
  color: #ff9900;
  margin-right: 4px;
}

.add-to-cart-btn {
  margin-top: auto;
  width: 100%;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .top-navbar .container {
    flex-direction: column;
    gap: 15px;
  }

  .search-area {
    max-width: 100%;
    margin: 15px 0;
  }

  .user-actions {
    width: 100%;
    justify-content: space-around;
  }
}

/* PC端适配样式 */
@media (min-width: 1200px) {
  .container {
    max-width: 1600px;
    padding: 0 50px;
  }

  .top-navbar {
    padding: 25px 0;
  }

  .logo-area h1 {
    font-size: 28px;
  }

  .search-area {
    max-width: 700px;
  }

  .user-actions {
    gap: 25px;
  }

  .user-actions .el-button {
    font-size: 16px;
  }

  .banner-section .el-carousel {
    height: 450px !important;
  }

  .product-card {
    transition: all 0.4s ease;
  }

  .product-card:hover {
    transform: translateY(-8px);
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
  }
}
</style>